package com.ys.utils.spring.properties;

import com.ys.utils.base.j2se.Logger;
import com.ys.utils.spring.config.SysConfigInfo;
import com.ys.utils.spring.config.SysErrorCode;
import com.ys.web.sys.config.SysConfigDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * Description
 * Created by 王伟
 * Date create on 15:37 2019/11/13.
 */
@Configuration
public class SysConfig {
    @Autowired
    private SysConfigDao sysConfigDao;
    private static SysConfigDao configDao;

    @PostConstruct
    private void init(){
        configDao = sysConfigDao;
        loadSysConfig();
        /* boot 配置文件打包，所有公共配置走数据库 */
        new Thread(()->{
            while (true) {
                try {
                    Thread.sleep(60*1000);
                    loadSysConfig();
                } catch (Exception e) {
                    Logger.error("系统配置加载出错:", e);
                }
            }
        }).start();
    }

    private static void loadSysConfig(){
        //加载配置中心错误码
        List<SysErrorCode> SysErrorCodes = configDao.sysErrorCode();
        for(SysErrorCode SysErrorCode : SysErrorCodes){
            Config.pp.put(SysErrorCode.errorCode, SysErrorCode.errorMsg);
        }

        //加载系统配置
        List<SysConfigInfo> sysConfigs = configDao.sysConfig();
        for(SysConfigInfo sysConfig : sysConfigs){
            Config.pp.put(sysConfig.configKey, sysConfig.configValue);
        }

        //加载oss配置
        List<SysConfigInfo> ossConfigs = configDao.ossConfig();
        for(SysConfigInfo ossConfig : ossConfigs){
            Config.pp.put(ossConfig.configKey, ossConfig.configValue);
        }

        //加载资金配置
        List<SysConfigInfo> walletConfigs = configDao.walletConfig();
        for(SysConfigInfo ossConfig : walletConfigs){
            Config.pp.put(ossConfig.configKey, ossConfig.configValue);
        }
    }

    public static int addBlackIp(String ip){
        return configDao.addBlackIp(ip);
    }
}
